<?php

class cp extends Module {
	
	public function __construct () {
		parent::__construct (__CLASS__);
	}
	
	public function __default () {
		return $this->dir ();
	}
	
	public function dir () {
		$objectsController = ObjectsController::getInstance();
		
		$oTypeItem = TypesController::getInstance()->getTypeByName('cp_item');
		
		$dirId = 0;
		if (getRequest ('param0','bool')) {
			$dirId = getRequest ('param0','int');
		}
		
		if (getRequest('delete','bool') && isset($_POST['cp_items']) && is_array($_POST['cp_items'])) {
			foreach ($_POST['cp_items'] as $itemId) {
				if ($object = $objectsController->getObject($oTypeItem, $itemId)) {
					$object->delete();
				}
			}
			
			redirect(HTTP_HOST . '/admin' . ($dirId == 0 ? '' : '/cp/dir/' . $dirId) . '?deleted');
		}
		
		$sel = new Selection;
		$sel->addType ($oTypeItem);
		$sel->addFilter ('rel_id', $dirId);
		$sel->setOrder ('title');
		
		$aObjects = $objectsController->getObjectsList ($sel->getList ());
		
		$response = new ModuleResponse;
		$response->setTemplate ('cp/itemsList');
		$response->setAttribute ('dir-id', $dirId);
		
		if (getRequest('deleted','bool')) {
			$response->addObject(new SystemMessage(lang('admin_cp_item_deleted',__CLASS__)));
		}
		if (getRequest('added','bool')) {
			$response->addObject(new SystemMessage(lang('admin_cp_item_added',__CLASS__)));
		}
		
		foreach ($aObjects as $object) {
			$response->addObject ($object);
		}
		
		return $response;
	}
	
	public function js_add_item() {
		$oTypeItem = TypesController::getInstance()->getTypeByName('cp_item');
		
		$object = new Object($oTypeItem);
		
		$aValues = $this->getRequestData('new', $oTypeItem);
		
		if (isset($aValues['link_module']) && $aValues['link_module'] == '') {
			$aValues['link_module'] = null;
		}
		
		if (isset($aValues['link_method']) && $aValues['link_method'] == '') {
			$aValues['link_method'] = null;
		}
		
		$object->setValues($aValues);
		
		if ($object->getValue('title') == '') {
			$this->flush('<script type="text/javascript">parent.cpSettingsError("' . lang('admin_error_new_item_no_title',__CLASS__) . '")</script>');
		}
		
		if ($object->getValue('type') == 'link' && !$object->getValue('link_module')) {
			$this->flush('<script type="text/javascript">parent.cpSettingsError("' . lang('admin_error_new_item_no_module',__CLASS__) . '")</script>');
		}
		
		if (isset($_FILES['icon']) && $_FILES['icon']['name'] != '') {
			$info = pathinfo($_FILES['icon']['name']);
			
			$path = '/images/cp/' . md5($object->getValue('title') . time()) . '.' . $info['extension'];
			if (FilesController::uploadFile($_FILES['icon'], DOC_ROOT . $path)) {
				$object->setValue('icon', $path);
			}
		} elseif (isset($_POST['icon_path']) && $_POST['icon_path'] != '') {
			$object->setValue('icon', $_POST['icon_path']);
		}
		
		$object->createNew();
		
		$this->flush('<script type="text/javascript">parent.document.location.href = "' . HTTP_HOST . '/admin/cp/dir/' . $object->getValue('rel_id') . '?added";</script>');
		
	}
	
	public function getPath ($dirId = 0, $module = false, $method = false) {
		$oTypeItem = TypesController::getInstance()->getTypeByName ('cp_item');
		$objectsController = ObjectsController::getInstance ();
		
		$response = new ModuleResponse;
		
		if ($module) {
			if ($method === false || $method == '__admin' || $method == '__default') {
				$method = null;
			}
			
			$sel = new Selection;
			$sel->addType ($oTypeItem);
			$sel->addFilter ('link_module', $module);
			$sel->addFilter ('link_method', $method);
			
			$res = $sel->getList ();
			
			if (!count ($res)) {
				return $response;
			}
			
			$dirId = $res[0][0];
		}
		
		if ($dirId == 0) {
			return $response;
		}
		
		$aObjects = array ();
		
		$this->detectObject ($dirId, $aObjects, $oTypeItem, $objectsController);
		
		ksort ($aObjects);
		
		foreach ($aObjects as $object) {
			$response->addObject ($object);
		}
		
		return $response;
	}
	
	public function ajax_get_tree() {
		$this->setResponseFormat('xml');
		
		$oTypeItem = TypesController::getInstance()->getTypeByName ('cp_item');
		
		$sel = new Selection;
		$sel->addType($oTypeItem);
		$sel->addFilter('type','dir');
		$sel->setOrder('title');
		
		$aObjects = ObjectsController::getInstance()->getObjectsList($sel->getList());
		
		$aRelated = array ();
		
		foreach ($aObjects as $object) {
			$aRelated[$object->getValue('rel_id')][] = $object;
		}
		
		$aResult = array();
		
		if (isset($aRelated[0])) {
			$this->buildListByParent($aRelated[0], $aRelated, $aResult, 0);
		}
		
		$response = new ModuleResponse;
		
		foreach ($aResult as $object) {
			$response->addObject($object);
		}
		
		return $response;
	}
	
	public function ajax_load_favorites () {
		$objectsController = ObjectsController::getInstance ();
		$typesController = TypesController::getInstance();
		
		$sel = new Selection;
		$sel->addType($typesController->getTypeByName ('favorite'));
		$sel->addFilter('user_id', ExplaySession::getUserId());
		$sel->addSelectedProperty('cp_item_id');
		
		$res = $sel->getList();
		
		$aItemsIds = array();
		
		foreach($res as $row) {
			$aItemsIds[] = $row['cp_item_id'];
		}
		
		$sel = new Selection;
		$sel->addType($typesController->getTypeByName('cp_item'));
		$sel->addFilterIn('id', $aItemsIds);
		$sel->setOrder('title');
		
		$aObjects = ObjectsController::getInstance()->getObjectsList($sel->getList());
		
		$response = new ModuleResponse;
		$response->setTemplate('cp/favoritesList');
				
		foreach($aObjects as $object) {
			$response->addObject($object);
		}
		
		return $response;
	}
	
	public function ajax_add_favorite () {
		$this->expectSecureGET ();
		
		$objectsController = ObjectsController::getInstance ();
		$typesController = TypesController::getInstance();
		
		$oTypeFav = $typesController->getTypeByName ('favorite');
		
		$id = getRequest ('param0','int');
		
		if (!$object = $objectsController->getObject($typesController->getTypeByName('cp_item'), $id)) {
			$this->flush((string) new Array2XML('result',array(0)), 'text/xml');
		}
		
		$sel = new Selection;
		$sel->addType($oTypeFav);
		$sel->addFilter('user_id', ExplaySession::getUserId());
		$sel->addFilter('cp_item_id', $id);
		
		if (count($sel->getTotalCount() == 0)) {
			$oFav = new Object($oTypeFav);
			$oFav->setValues(array(
				'user_id' => ExplaySession::getUserId(),
				'cp_item_id' => $id
			));
			$oFav->createNew();
		}
		
		$this->flush((string) new Array2XML('result',array(1)), 'text/xml');
	}
	
	public function ajax_delete_favorite () {
		$this->expectSecureGET ();
		
		$oTypeFav = TypesController::getInstance()->getTypeByName ('favorite');
		
		$id = getRequest ('param0','int');
		
		$sel = new Selection;
		$sel->addType($oTypeFav);
		$sel->addFilter('user_id', ExplaySession::getUserId());
		$sel->addFilter('cp_item_id', $id);
		
		$res = $sel->getList();
		
		if (count($res)) {
			$object = ObjectsController::getInstance()->getObject($oTypeFav, $res[0][0]);
			$object->delete();
		}
		
		$this->flush((string) new Array2XML('result',array(1)), 'text/xml');
	}
	
	private function detectObject ($id, array &$aObjects, Type $oTypeItem, ObjectsController $objectsController) {
		if ($oItem = $objectsController->getObject ($oTypeItem, $id)) {
			$aObjects[$id] = $oItem;
			
			if ($relId = $oItem->getValue ('rel_id')) {
				$this->detectObject ($relId, $aObjects, $oTypeItem, $objectsController);
			}
		}
	}
	
	private function buildListByParent (array &$aLevel, array &$aRelated, array &$aResult, $level) {
		foreach ($aLevel as $object) {
			$object->setAttribute('level', $level);
			$aResult[] = $object;
			
			if (isset($aRelated[$object->getId()])) {
				$this->buildListByParent($aRelated[$object->getId()], $aRelated, $aResult, $level+1);
			}
		}
	}
	
}